package com.xuecheng.manage_cms.controller;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.framework.web.BaseController;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/cms/utils")
public class UploadUtils extends BaseController {
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    //存文件
    @PostMapping("/upload")
    public Map saveFile(MultipartFile file) throws Exception {
        Map<String,String> result = new HashMap<>();
        InputStream inputStream = file.getInputStream();
        ObjectId objectId = gridFsTemplate.store(inputStream, file.getOriginalFilename());
        result.put("objectId",objectId.toString());
        result.put("filename",file.getOriginalFilename());
        return result;
    }

    //取文件
    @GetMapping("/getFile/{id}")
    public void getFile(@PathVariable("id") String id) throws IOException {
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        //打开下载流对象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridfsresource
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
        //获取流中的数据
        String content = IOUtils.toString(gridFsResource.getInputStream(),"UTF-8");
        System.out.println(content);
    }
    //取文件
    @GetMapping("/downloadFile/{id}")
    public String downloadFile(@PathVariable("id") String id) throws IOException {
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        //打开下载流对象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridfsresource
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);

        //获取流中的数据
        String content = IOUtils.toString(gridFsResource.getInputStream(),"UTF-8");
        return content;
        /*InputStream in = gridFsResource.getInputStream();
        // 2. 告诉浏览器下载的方式以及一些设置
        // 解决文件名乱码问题，获取浏览器类型，转换对应文件名编码格式，IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
        String agent = request.getHeader("user-agent");
        String filename = this.getFileName(id);
        if (agent.contains("FireFox")) {
            filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        } else {
            filename = URLEncoder.encode(filename, "UTF-8");
        }
        // 设置下载文件的mineType，告诉浏览器下载文件类型
        String mineType = request.getServletContext().getMimeType(filename);
        response.setContentType(mineType);
        // 设置一个响应头，无论是否被浏览器解析，都下载
        response.setHeader("Content-disposition", "attachment; filename=" + filename);
        // 将要下载的文件内容通过输出流写到浏览器
        OutputStream out = response.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        if(null != out){
            out.close();
        }
        if(null != in){
            in.close();
        }*/
    }

    //取文件名称
    @GetMapping("/templateFile_getName/{id}")
    public String getFileName(@PathVariable("id") String id) throws IOException {
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        String filename = gridFSFile.getFilename();
        return filename;
    }
}
